package com.sntk.organauthomanager.infrastructure.dao;

import com.sntk.organauthomanager.domain.model.RoleIdentify;
import com.sntk.organauthomanager.domain.model.UserRole;
import com.sntk.organauthomanager.domain.repository.UserRoleRepository;
import com.sntk.organauthomanager.infrastructure.convert.UserRoleConvert;
import com.sntk.organauthomanager.infrastructure.db.entity.UserRoleEntity;
import com.sntk.organauthomanager.infrastructure.db.repository.UserRoleDBRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName: UserRoleDBRepositoryImpl
 * @author: wgchao
 * @createTime: 2020/7/21 6:19 PM
 * @Description: TODO
 */
@Component
public class UserRoleRepositoryImpl implements UserRoleRepository {
    @Autowired
    private UserRoleDBRepository userRoleDBRepository;
    @Autowired
    private UserRoleConvert userRoleConvert;

    @Override
    public void add(UserRole userRole, String operator) {
        //只有新增没有修改 新增前删除原有关系
        List<UserRoleEntity> userRoleEntities = userRoleDBRepository.findAllByUname(userRole.getUname());
        if(userRoleEntities!=null && !userRoleEntities.isEmpty()){
            userRoleDBRepository.deleteAll(userRoleEntities);
            userRoleDBRepository.findAllByUname(userRole.getUname());//重新查询清除缓存防止唯一键冲突
        }
        userRoleEntities = userRoleConvert.convert(userRole);
        if(userRoleEntities!=null && !userRoleEntities.isEmpty()){
            userRoleEntities = userRoleDBRepository.saveAll(userRoleEntities);
        }
    }

    @Override
    public UserRole findByKey(String s) {
        List<UserRoleEntity> userRoleEntities = userRoleDBRepository.findAllByUname(s);
        if(userRoleEntities!=null && !userRoleEntities.isEmpty()){
            return userRoleConvert.convert(userRoleEntities);
        }
        return null;
    }

    @Override
    public void delete(String s, String operator) {
        List<UserRoleEntity> userRoleEntities = userRoleDBRepository.findAllByUname(s);
        if(userRoleEntities==null || userRoleEntities.isEmpty()){
            return;
        }
        userRoleDBRepository.deleteAll(userRoleEntities);
    }

    @Override
    public void removeByUser(String uname, String operator) {
        userRoleDBRepository.deleteAllByUname(uname);
    }

    @Override
    public void removeByRole(RoleIdentify roleIdentify, String operator) {
        userRoleDBRepository.deleteAllByRoleCodeAndInstitutionNumber(roleIdentify.getRoleCode(), roleIdentify.getInstitutionNumber());
    }
}
